package com.jambo.yudada.manager;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.jambo.yudada.config.OSSConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;

@Service // 添加@Component注解，使其成为Spring Bean
@Slf4j
public class OSSManager {

    @Resource
    private OSSConfig ossConfig;

    /**
     * 文件上传
     */
    public String upload(String objectName, InputStream inputStream) {
        OSS ossClient = ossConfig.getOssClient();
        String url = "";

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucket(),
                    objectName,
                    inputStream
            );

            ossClient.putObject(putObjectRequest);

            // 生成访问URL
            url = String.format("https://%s.%s/%s",
                    ossConfig.getBucket(),
                    ossConfig.getEndpoint(),
                    objectName
            );

            log.info("文件上传成功: {}", url);
        } catch (OSSException | ClientException e) {
            log.error("OSS上传异常: {}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return url;
    }
}